import * as uuid from "uuid";
import Typings from "../typings";

// 时间戳转化时间格式
export const formatTimestamp: (
  timestamp: string | number,
  format?: string
) => string = (timestamp, format = "YYYY-MM-DD HH:mm:ss") => {
  const date = new Date(timestamp);

  if (isNaN(date.getTime())) {
    return "Invalid Date";
  }

  // 位数补齐
  const pad = (num: number) => num.toString().padStart(2, "0");

  const replacements: { [propName: string]: string } = {
    YYYY: date.getFullYear().toString(),
    YY: String(date.getFullYear()).slice(-2).toString(),
    MM: pad(date.getMonth() + 1).toString(),
    M: (date.getMonth() + 1).toString(),
    DD: pad(date.getDate()).toString(),
    D: date.getDate().toString(),
    HH: pad(date.getHours()).toString(),
    H: date.getHours().toString(),
    hh: pad(date.getHours() % 12 || 12).toString(),
    h: (date.getHours() % 12 || 12).toString(),
    mm: pad(date.getMinutes()).toString(),
    m: date.getMinutes().toString(),
    ss: pad(date.getSeconds()).toString(),
    s: date.getSeconds().toString(),
  };

  return format.replace(
    /YYYY|YY|MM|M|DD|D|HH|H|hh|h|mm|m|ss|s/g,
    (match: string) => replacements[match] || "--"
  );
};

export const transform: (
  code: Typings.Common.baseValue,
  options: Typings.Common.option[]
) => string = (code = "", options = []) => {
  return options.find((i) => i.code === code)?.name || "--";
};

export const matchTagObj: (
  code: Typings.Common.baseValue,
  options: Typings.Common.option[]
) => Typings.Common.option = (code = "", options = []) => {
  return (
    options.find((i) => i.code === code) || {
      name: String(code),
      code,
      type: "primary",
    }
  );
};

// 生成一个 uuid
export const getUuid: () => string = () => {
  return uuid.v4();
};

// 延迟函数
export const sleep = (t: number = 300) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, t);
  });
};
